/*
 * DataSourceLoginModule.java
 *
 * Created on 4 Ноябрь 2006 г., 16:12
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package authregistration;

import java.util.*;
import java.sql.*;
//import authentification.Client;
import crypto.*;
import javax.naming.*;
import javax.security.auth.spi.LoginModule;
import javax.security.auth.*;
import javax.security.auth.callback.*;
import javax.security.auth.login.*;

import javax.sql.*;

/**
 * JAAS LoginModule configure string in {$HOME}/jre/bin/security/java.security
 */
public class DataSourceLoginModule implements LoginModule {
    CallbackHandler handler;
    Subject subject;
    Map sharedState;
    Map options;

    /**
     * login flag
     */
    private boolean loginPassed = false;

    public DataSourceLoginModule() {}

    /**
     * 
     * @param subject 
     * @param handler 
     * @param sharedState 
     * @param options 
     */
    public void initialize(Subject subject, CallbackHandler handler,
                           Map sharedState, Map options) {
        this.handler = handler;
        this.options = options;
        this.sharedState = sharedState;
        this.subject = subject;
    }

    /**
     * Login method starts when configure ends
     * @throws javax.security.auth.login.LoginException 
     * @return login or not login?This is the question.
     */
    public boolean login() throws LoginException {
        String name = "";
        String pass = "";
        Context env = null;
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;
        DataSource pool = null;

        boolean passed = false;
        try {

            Class.forName(com.mysql.jdbc.Driver.class.getName());
            Callback[] callbacks = new Callback[2];
            callbacks[0] = new NameCallback("Username:");
            callbacks[1] = new PasswordCallback("Password:", false);
            //
            handler.handle(callbacks);
            //gets name and password
            NameCallback namec = (NameCallback) callbacks[0];
            name = namec.getName();

            PasswordCallback passc = (PasswordCallback) callbacks[1];
            pass = new String(passc.getPassword());
            ///Looking for Datasource to check name and password
            /*conn = DriverManager.getConnection(
                    "localhost:3306:user on localhost:user",
                "lesha", "tolstyak");*/
            String seed =new String(new Double(Math.random()).toString());
            String hash = crypto.GetPassword.setHash(name,pass,seed);    
            //env=(Context) new InitialContext().lookup("java:comp/env");
            //pool = (DataSource) env.lookup("jdbc/user");
            //conn = pool.getConnection();
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/user?user=root&password=tolstyak");
            stmt = conn.createStatement();
            //Some sql commands

            String sqlname = "select * from gameusers where username ='" + name +
                             "'";
            String sqlpass = "select * from gameusers where password ='" + pass +
                             "'";

            rs = stmt.executeQuery(sqlname);

            passed = rs.next();
            if (!passed) {
                loginPassed = false;
                System.out.print("sdgsadgsg");
                throw new FailedLoginException("The username is incorrect");
            }else{
                String basehash = rs.getString("password");
  //              crypto.UserPasswordCheck.compareWith=crypto.UserPasswordCheck.putIntoDateBase(name, pass);
                if(!crypto.UserPasswordCheck.auth(hash,name,seed,basehash)){
                    throw new FailedLoginException("The password is incorrect");
                }else {
                loginPassed = true;
                return true;
                }
            }

            //check password;
            /*rs = stmt.executeQuery(sqlpass);
            passed = rs.next();
            if (!passed) {
                throw new FailedLoginException("The password is incorrect");
            } else {
                loginPassed = true;
                return true;
            }*/
        } catch (Exception e) {
            throw new LoginException(e.getMessage());
        } finally {
            try {
                conn.close();
            } catch (SQLException sqle) {
            }
        }
    }

    /**
     * after authentification
     */
    public boolean commit() throws LoginException {
        return loginPassed;
    }

    public boolean abort() throws LoginException {
        boolean bool = loginPassed;
        loginPassed = false;
        return bool;
    }

    public boolean logout() throws LoginException {
        loginPassed = false;
        return true;
    }

}

